package com.now.doublepointer;

/**
 * 189. 轮转数组
 * 给你一个数组，将数组中的元素向右轮转 k 个位置，其中 k 是非负数。
 * 输入: nums = [1,2,3,4,5,6,7], k = 3
 * 输出: [5,6,7,1,2,3,4]
 */
public class Rotate {

    /**
     * 循环过多，超出时间限制
     * @param nums
     * @param k
     */
    public static void rotate(int[] nums, int k) {
        int length = nums.length;
        while (k > 0) {
            int data = 0;
            data = nums[length - 1];
            for (int i = length - 1; i > 0; i--) {
                nums[i] = nums[i - 1];
            }
            nums[0] = data;
            k--;
        }
    }

    /**
     * 数组翻转
     * nums = "----->-->"; k =3
     * result = "-->----->";
     *
     * reverse "----->-->" we can get "<--<-----"
     * reverse "<--" we can get "--><-----"
     * reverse "<-----" we can get "-->----->"
     * @param nums
     * @param k
     */
    public static void rotate1(int[] nums, int k) {
        int end= nums.length;
        reverse(nums,0,end-1);
        reverse(nums,0,(k%end) -1);
        reverse(nums,k%end,end-1);

    }
    public static void reverse(int[] nums,int start, int end){
        while(start<=end){
            int data = nums[start];
            nums[start]=nums[end];
            nums[end]=data;
            start++;
            end--;
        }
    }
    public static void main(String[] args) {
        int[] nums = {1,2,3,4,5,6,7};
        int k = 3;
        rotate1(nums, k);
        System.out.println(nums);
    }
}
